<script>
import { reactive } from "vue";
import Taro from "@tarojs/taro";
import { setToken, clear, getToken, setTokenInfo } from "@/utils/storage";
import { icLogo, bgLoginHeader } from "@/assets";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { setUserInfo, setDicMap, getUserInfo } from "@/utils/storage";
import { loadDicMap } from "@/api/dicApi";
import { getBaseData, getUserinfoApi, login } from "@/api/userApi";
import { wxRegisterApi, recordOpenIdApi } from "./api";

export default {
  name: "Login",
  setup() {
    const state = reactive({
      username: "",
      password: "",
      grant_type: "password",
      servicePhoneNum: "+86-755-82789938",
    });

    //清空本地 storage
    if (getToken()) {
      const { account } = getUserInfo();
      state.username = account;
      clear();
    }
    const { navigateTo } = useTzRouter();

    const handleClick = () => {
      if (!state.username || !state.username.trim()) {
        $TzNotify.danger("请输入账号");
        return;
      }
      if (!state.password || !state.password.trim()) {
        $TzNotify.danger("请输入密码");
        return;
      }
      // login(state)
      login({
        loginCode: state.username,
        password: state.password,
      })
        .then((res) => {
          setTokenInfo(res.data);
          return setToken(res.data.accessToken);
        })
        .then(() => {
          initStorageData();
          $TzNotify.success("登录成功");
          // 发送 res.code 到后台换取 openId
          return recordOpenIdApi({ tmpCode: state.wxLoginCode });
        })
        .catch((err) => {
          $TzNotify.danger(err.data?.msg || "登录失败");
        });
    };

    const initStorageData = async () => {
      Promise.all([getBaseData(), getUserinfoApi()]).then((res) => {
        const dicMap = res[0].data.dicMap || {};
        const userInfo = res[1].data;

        const { hkBund, userType: _userType } = userInfo;
        const hasHkBund = hkBund === 1;

        setUserInfo(
          Object.assign(userInfo, {
            account: state.username.toString(),
            hasHkBund,
          })
        );
        //加载本地以及线上的数据字典
        loadDicMap(dicMap);
        const userType = {
          isPersonal: _userType === "1", //个人版
          isDriver: _userType === "2", //司机
          isOperator: _userType === "0", //操作员
          value: _userType,
        };
        Object.assign(dicMap, { userType });
        setDicMap(dicMap);
        Taro.switchTab({
          url: "/pages/home/index",
        });
      });
    };

    const handleCall = () => {
      Taro.makePhoneCall({
        phoneNumber: state.servicePhoneNum,
      }).catch((err) => {
        console.warn(err);
      });
    };

    Taro.login().then((res) => {
      state.wxLoginCode = res.code;
    });
    // 获取手机号码
    const handleGetPhoneNumber = (e) => {
      Taro.checkSession({
        success() {
          const { iv, encryptedData } = e.detail;
          if (!iv || !encryptedData) return;
          wxRegisterApi({
            tmpCode: state.wxLoginCode,
            encryptData: encryptedData,
            iv,
          })
            .then((res) => {
              if (res.data?.accessToken) {
                setTokenInfo(res.data);
                return setToken(res.data.accessToken);
              }
            })
            .then(() => {
              initStorageData();
              $TzNotify.success("登录成功");
            })
            .catch((err) => {
              $TzNotify.danger(err.data.msg);
              Taro.login().then((res) => {
                state.wxLoginCode = res.code;
              });
            });
        },
        fail() {
          Taro.login().then((res) => {
            state.wxLoginCode = res.code;
          });
        },
      });
    };

    return () => (
      <tz-view class="login">
        <tz-view class="header">
          <tz-image src={bgLoginHeader} class="header_bg"></tz-image>
          <tz-image src={icLogo} class="logo"></tz-image>

          <text class="title">泰洲车辆确报系统</text>
          <text class="title_type">微信小程序版</text>
        </tz-view>
        <tz-view class="section">
          <tz-view class="title">欢迎登录</tz-view>
          <tz-form>
            <tz-cell title="账号" border>
              <tz-input
                clearable
                v-model={state.username}
                placeholder="请输入账号"
              />
            </tz-cell>
            <tz-cell title="密码">
              <tz-input
                v-model={state.password}
                type="password"
                placeholder="请输入密码"
                clearable
              />
            </tz-cell>
          </tz-form>
        </tz-view>
        <tz-button class="login-btn" type="primary" onClick={handleClick}>
          登录
        </tz-button>
        <tz-button
          openType="getPhoneNumber"
          class="wechat-login-btn"
          type="success"
          onGetphonenumber={handleGetPhoneNumber}
        >
          <tz-icon name="wechat"></tz-icon>
          微信账号快速登录
        </tz-button>
        <tz-view class="sub-btn-area">
          <tz-view
            class="register-btn"
            onClick={() =>
              navigateTo({ path: "/pages/subUser/register/index" })
            }
          >
            新用户注册
          </tz-view>
          <tz-view
            class="findpwd-btn"
            onClick={() => navigateTo({ path: "/pages/subUser/findPwd/index" })}
          >
            找回密码
          </tz-view>
        </tz-view>
        <tz-view class="help-info">
          <text>当前版本:V1.2.0H</text>
          <view onClick={handleCall}>
            客服电话：<text>{state.servicePhoneNum}</text>
          </view>
        </tz-view>
      </tz-view>
    );
  },
};
</script>

<style lang="scss">
.login {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .header {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    color: $white;
    .header_bg {
      width: 100%;
      height: 200px;
    }
    .logo {
      top: 13px;
      left: 10px;
      position: absolute;
      width: 43px;
      height: 43px;
    }

    .title {
      font-size: 28px;
      position: absolute;
      top: 65px;
      width: 100%;
      text-align: center;
    }

    .title_type {
      position: absolute;
      font-size: 21px;
      top: 110px;
      width: 100%;
      text-align: center;
    }
  }

  .section {
    display: flex;
    flex-direction: column;
    padding-top: 6px;
    width: 100%;

    .title {
      color: #999;
      height: 34px;
      line-height: 33px;
      font-size: 14px;
      padding: 0 15px;
      @extend %bb1;
    }
    .tz-form {
      padding: 0 15px;
      background: $white;
      @extend %bb1;
    }
  }

  .login-btn,
  .wechat-login-btn {
    width: 345px;
    margin-top: 20px;
    height: 44px;
    .tz-icon {
      margin-right: 3px;
    }
  }
  .sub-btn-area {
    width: 345px;
    font-size: 14px;
    padding-bottom: 5px;
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
  }

  // 后续删除此样式
  .findpwd-btn-temp {
    padding: 0px 15px 5px;
    margin-top: 16px;
    font-size: 14px;
    text-align: right;
    align-self: flex-end;
  }

  .help-info {
    color: $success-color-end;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 12px;
    line-height: 20px;
    margin-top: 10px;
  }
}
</style>
